
package com.kugou.game.sdk.ui.activity;

import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.core.FolderManager;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.core.VipManager;
import com.kugou.game.sdk.interfaces.OnRequestListener;
import com.kugou.game.sdk.interfaces.OnRequestUserIdCardListener;
import com.kugou.game.sdk.ui.dialog.IdentitySetDialog;
import com.kugou.game.sdk.ui.dialog.ModifyUserPhotoDialog;
import com.kugou.game.sdk.ui.dialog.SetNickNameDialog;
import com.kugou.game.sdk.ui.fragment.BindPhoneFragment;
import com.kugou.game.sdk.ui.fragment.UpdateBindPhoneFragment;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.ui.widget.RoundImageView;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.AsyncImageLoader;
import com.kugou.game.sdk.utils.AsyncImageLoader.ImageCallback;
import com.kugou.game.sdk.utils.NetWorkUtil;
import com.kugou.game.sdk.utils.Rx;
import com.kugou.game.sdk.utils.ToastUtil;
import com.kugou.game.sdk.utils.ZoomBitmapUtil;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UserInfoActivity extends BaseCommonTitleFragmentActivity implements OnClickListener,
        ImageCallback {

    private RoundImageView ivUserPhoto;// 头像

    private ImageView ivUserVipPhoto;// vip角标

    private TextView tvUserName;// 用户名

    private TextView tvNickName;// 昵称

    private TextView tvRealName;// 真实姓名

    private TextView tvUserIdNum;// 身份证号

    private TextView tvBindPhone;// 安全手机

    private TextView tvSecurityEmail;// 安全邮箱

    private TextView tvNickNameItem;

    private RelativeLayout rlRealName, rlUserIdNum, rlNickName;

    private RelativeLayout rlEntryBindPhone, rlEntrySecurityEmail, rlChargeHistory;

    private ModifyUserPhotoDialog modifyUserPhotoDialog;

    private IdentitySetDialog identitySetDialog;

    private SetNickNameDialog setNickNameDialog;

    private AsyncImageLoader mAsyncImageLoader;

    private LoadingView mLoadingView;

    private String realName, userIdNum, userPsw, nickName;

    private User user;

    private static final int MSG_START_UPLOAD = 0x0A;

    private static final int MSG_UPLOAD_SUCCESS = 0x1A;

    private static final int MSG_UPLOAD_FAIL = 0x2A;

    private static final int MSG_START_UPDATE = 0x3A;

    private static final int MSG_UPDATE_SUCCESS = 0x4A;

    private static final int MSG_UPDATE_FAIL = 0x5A;

    private static final int MSG_START_MODIFY = 0x6A;

    private static final int MSG_START_UPDATE_NICKNAME = 0x7A;

    private static final int MSG_UPDATE_NICKNAME_SUCCESS = 0x8A;

    private static final int MSG_UPDATE_NICKNAME_FAIL = 0x9A;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        user = UserManager.getInstance().getCurrentUserInternal();
        int layoutId = Rx.layout.kg_activity_user_info;
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            layoutId = Rx.layout.kg_activity_user_info_land;
        }
        if (layoutId != 0) {
            setContentView(layoutId);
            setCommonTitle(Rx.string.kg_personal_info_activity);
            setCommonRightImageViewVisibility(View.GONE);
            initViews();
            initData();
        }
    }

    /**
     * 设置头像
     */
    public void setUserHead() {
        User user = UserManager.getInstance().getCurrentUserInternal();
        String imageUrl = user.getHeadIconUrl();
        String savePath = FolderManager.IMAGE_CACHE_FOLDER + AppUtil.getFileNameFromUrl(imageUrl);
        loadImage(imageUrl, savePath);
    }

    /**
     * 显示vip角标
     */
    private void showVipHeadIcon() {
        if (VipManager.getInstance().isVip()) {
            ivUserVipPhoto.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置用户名
     */
    private void setNickName() {
        tvNickNameItem.setText(TextUtils.isEmpty(user.getNickName()) ? "" : user.getNickName());
        tvNickName.setText(TextUtils.isEmpty(user.getNickName()) ? "" : user.getNickName());
        tvUserName.setText(TextUtils.isEmpty(user.getAccountName()) ? "账号： " : "账号："
                + user.getAccountName());
    }

    /**
     * 设置姓名身份证
     */
    private void setIDInfo() {
        if (!TextUtils.isEmpty(user.getTrueName())) {
            String realName = user.getTrueName();
            String realNameReplace = realName.replaceAll(realName.substring(1),
                    strReplaceCount(realName.length() - 1));
            tvRealName.setText(realNameReplace);
            tvRealName.setCompoundDrawables(null, null, null, null);
            tvUserIdNum.setText("已绑定");
            tvUserIdNum.setCompoundDrawables(null, null, null, null);
        } else {
            tvUserIdNum.setText("未绑定");
            rlRealName.setOnClickListener(this);
            rlUserIdNum.setOnClickListener(this);
        }
    }

    /**
     * 是否已绑定手机
     */
    private void checkBindphone() {
        if (!TextUtils.isEmpty(user.getBindPhoneNum())) {
            String phoneNum = user.getBindPhoneNum();
            String phoneNumReplace = phoneNum.replaceAll(phoneNum.substring(2, 9),
                    strReplaceCount(7));
            tvBindPhone.setCompoundDrawables(null, null, null, null);
            tvBindPhone.setText(phoneNumReplace);
        } else {
            tvBindPhone.setText("去设置");
            rlEntryBindPhone.setOnClickListener(this);
        }
    }

    /**
     * 是否已绑定安全邮箱
     */
    private void checkSecurityEmail() {
        if (!TextUtils.isEmpty(user.getSecurityEmail())) {
            String email = user.getSecurityEmail();
            String emailReplace = email.replaceAll(email.substring(2, email.indexOf("@")),
                    strReplaceCount(email.substring(2, email.indexOf("@")).length()));
            tvSecurityEmail.setCompoundDrawables(null, null, null, null);
            tvSecurityEmail.setText(emailReplace);
        } else {
            tvSecurityEmail.setText("去设置");
            rlEntrySecurityEmail.setOnClickListener(this);

        }
    }

    /**
     * 加载图片
     * 
     * @param imageUrl
     * @param savePath
     */
    private void loadImage(String imageUrl, String savePath) {
        if (mAsyncImageLoader == null)
            return;
        mAsyncImageLoader.loadImage(this, imageUrl, imageUrl, savePath, this);
    }

    /**
     * 真实姓名及身份证设置对话框
     */
    private void showIdentitySetDialog() {
        if (isFinishing()) {
            return;
        }
        if (identitySetDialog == null) {
            identitySetDialog = new IdentitySetDialog(UserInfoActivity.this);
        }
        identitySetDialog.setDialogTitle("姓名和身份证");
        identitySetDialog.setCancelText("取消");
        identitySetDialog.setOKBtnText("确定");
        identitySetDialog.setCancelable(false);
        identitySetDialog.setCancelClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                identitySetDialog.hideSoftInput();
                identitySetDialog.dismiss();
            }
        });
        identitySetDialog.setOKClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                identitySetDialog.hideSoftInput();
                realName = identitySetDialog.getRealName();
                userIdNum = identitySetDialog.getIdNumber();
                userPsw = identitySetDialog.getPassword();
                if (TextUtils.isEmpty(userPsw)) {
                    identitySetDialog.showPasswordErrorMsg();
                    return;
                }
                if (TextUtils.isEmpty(realName) || !realNameCheck(realName)) {
                    identitySetDialog.showRealNameErrorMsg();
                    return;
                } else {
                    identitySetDialog.hideRealNameErrorMsg();
                }
                if (TextUtils.isEmpty(userIdNum) || !idNumberCheck(userIdNum)) {
                    identitySetDialog.showIDNumErrorMsg();
                    return;
                } else {
                    identitySetDialog.hideIDNumErrorMsg();
                }
                identitySetDialog.dismiss();
                sendEmptyBackgroundMessage(MSG_START_UPDATE);
            }
        });
        identitySetDialog.show();
    }

    /**
     * 修改昵称对话框
     */
    private void showSetNickNameDialog() {
        if (isFinishing()) {
            return;
        }
        if (setNickNameDialog == null) {
            setNickNameDialog = new SetNickNameDialog(UserInfoActivity.this);
        }
        setNickNameDialog.setDialogTitle("修改昵称");
        setNickNameDialog.setCancelText("取消");
        setNickNameDialog.setOKBtnText("确定");
        setNickNameDialog.setCancelable(false);
        setNickNameDialog.setCancelClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                setNickNameDialog.hideSoftInput();
                setNickNameDialog.dismiss();
            }
        });
        setNickNameDialog.setOKClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                setNickNameDialog.hideSoftInput();
                nickName = setNickNameDialog.getNickName();
                if (TextUtils.isEmpty(nickName)) {
                    ToastUtil.showMsg("昵称不能为空");
                    return;
                }
                setNickNameDialog.dismiss();
                sendEmptyBackgroundMessage(MSG_START_UPDATE_NICKNAME);
            }
        });
        setNickNameDialog.show();
    }

    private void initViews() {
        mLoadingView = (LoadingView) findViewById(Rx.id.kg_loadingView);
        tvNickNameItem = (TextView) findViewById(Rx.id.kg_tv_user_nick_name);
        tvNickName = (TextView) findViewById(Rx.id.kg_tv_nickname);
        tvUserName = (TextView) findViewById(Rx.id.kg_tv_username);
        tvRealName = (TextView) findViewById(Rx.id.kg_tv_user_real_name);
        tvUserIdNum = (TextView) findViewById(Rx.id.kg_tv_user_id_num);
        tvBindPhone = (TextView) findViewById(Rx.id.kg_tv_have_bind_phone);
        tvSecurityEmail = (TextView) findViewById(Rx.id.kg_tv_have_security_email);
        rlNickName = (RelativeLayout) findViewById(Rx.id.kg_rl_user_nick_name);
        rlRealName = (RelativeLayout) findViewById(Rx.id.kg_rl_user_real_name);
        rlUserIdNum = (RelativeLayout) findViewById(Rx.id.kg_rl_user_id_num);
        rlEntryBindPhone = (RelativeLayout) findViewById(Rx.id.kg_rl_entry_bindphone);
        rlEntrySecurityEmail = (RelativeLayout) findViewById(Rx.id.kg_rl_entry_security_email);
        rlChargeHistory = (RelativeLayout) findViewById(Rx.id.kg_rl_user_charge_history);
        ivUserPhoto = (RoundImageView) findViewById(Rx.id.kg_iv_user_photo);
        ivUserPhoto.setmBorderColor(0x00ffffff);
        ivUserVipPhoto = (ImageView) findViewById(Rx.id.kg_iv_vip_head);
        ivUserPhoto.setOnClickListener(this);
        rlNickName.setOnClickListener(this);
        rlChargeHistory.setOnClickListener(this);

    }

    private void initData() {
        mAsyncImageLoader = new AsyncImageLoader();
        setUserHead();
        showVipHeadIcon();
        // ZoomBitmapUtil.getHeadPhoto(user);
        setNickName();
        setIDInfo();
        checkBindphone();
        checkSecurityEmail();
    }

    @Override
    public void onClick(View v) {
        if (v == ivUserPhoto) {
            modifyUserPhotoDialog = new ModifyUserPhotoDialog(this);
            modifyUserPhotoDialog.setOnTakePhotoListener(onTakePhotoListener);
            modifyUserPhotoDialog.setOnAlbumListener(onAlbumListener);
            modifyUserPhotoDialog.setOnCancelModifyListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    modifyUserPhotoDialog.dismiss();
                }
            });
            modifyUserPhotoDialog.show();
        } else if (v == rlRealName) {
            if (TextUtils.isEmpty(user.getTrueName()))
                showIdentitySetDialog();
            return;
        } else if (v == rlUserIdNum) {
            if (TextUtils.isEmpty(user.getTrueName()))
                showIdentitySetDialog();
            return;
        } else if (v == rlEntryBindPhone) {
            if (TextUtils.isEmpty(user.getBindPhoneNum())) {
                startActivity(CommonSdkActivity.creatIntent(UserInfoActivity.this,
                        BindPhoneFragment.class.getName(), Rx.string.kg_kugou_bind_phone_title));
            } else {
                startActivity(CommonSdkActivity.creatIntent(UserInfoActivity.this,
                        UpdateBindPhoneFragment.class.getName(),
                        Rx.string.kg_kugou_bind_phone_title));
            }
        } else if (v == rlEntrySecurityEmail) {
            startActivity(new Intent(getApplicationContext(), BindSecurityEmailActivity.class));
        } else if (v == rlNickName) {
            showSetNickNameDialog();
            setNickNameDialog.setNickName(user.getNickName());
        } else if (v == rlChargeHistory) {
            Intent intent = new Intent(UserInfoActivity.this, ChargeHistoryActivity.class);
            startActivity(intent);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode == ZoomBitmapUtil.NONE)
            return;
        // 拍照
        if (requestCode == ZoomBitmapUtil.PHOTOHRAPH) {
            // 设置文件保存路径这里放在跟目录下
            File picture = new File(Environment.getExternalStorageDirectory() + "/temp.png");
            ZoomBitmapUtil.startPhotoZoom(UserInfoActivity.this, Uri.fromFile(picture));
        }
        if (intent == null)
            return;
        // 读取相册缩放图片
        if (requestCode == ZoomBitmapUtil.PHOTOZOOM) {
            ZoomBitmapUtil.startPhotoZoom(UserInfoActivity.this, intent.getData());
        }
        // 处理结果
        if (requestCode == ZoomBitmapUtil.PHOTORESOULT) {
            // Bundle extras = intent.getExtras();
            // if (extras != null) {
            // try {
            sendEmptyBackgroundMessage(MSG_START_UPLOAD);
            // } catch (Exception e) {
            // e.printStackTrace();
            // }
            // }
        }
    }

    /*
     * 拍照
     */
    private OnClickListener onTakePhotoListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.png")));
            startActivityForResult(intent, ZoomBitmapUtil.PHOTOHRAPH);
            modifyUserPhotoDialog.dismiss();
        }
    };

    /*
     * 从相册中选取
     */
    private OnClickListener onAlbumListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            modifyUserPhotoDialog.dismiss();
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    ZoomBitmapUtil.IMAGE_UNSPECIFIED);
            startActivityForResult(intent, ZoomBitmapUtil.PHOTOZOOM);
        }
    };

    private boolean realNameCheck(String s) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]{2,}");
        Matcher m = p.matcher(s);
        return m.matches();
    }

    private boolean idNumberCheck(String s) {
        Pattern p = Pattern.compile("[0-9]{18}");
        Matcher m = p.matcher(s);
        return m.matches();
    }

    @Override
    public void handleBackgroundMessage(Message msg) {

        switch (msg.what) {
            case MSG_START_UPDATE:
                sendEmptyUiMessage(MSG_START_MODIFY);

                if (identitySetDialog.getRealName() == null
                        || identitySetDialog.getIdNumber() == null) {
                    sendEmptyUiMessage(MSG_UPDATE_FAIL);
                    return;
                }
                final Message message = new Message();
                UserManager.getInstance().updateUserIdCard(user.getAccountName(),
                        identitySetDialog.getPassword(), identitySetDialog.getIdNumber(),
                        identitySetDialog.getRealName(), new OnRequestUserIdCardListener() {

                            @Override
                            public void onSuccess() {
                                message.what = MSG_UPDATE_SUCCESS;
                            }

                            @Override
                            public void onFailed(String errorMsg) {
                                message.what = MSG_UPDATE_FAIL;
                                message.obj = errorMsg;
                                ToastUtil.showMsg(errorMsg);
                            }
                        });
                sendUiMessage(message);
                break;
            case MSG_START_UPLOAD:
                if (!NetWorkUtil.isNetworkAvailable(this)) {
                    ToastUtil.showMsg("当前网络不可用，请检查网络...");
                    return;
                }
                // 开始上传头像
                sendEmptyUiMessage(MSG_START_MODIFY);
                UserManager.getInstance().updateUserHead(user.getAccountName(),
                        new File(FolderManager.USER_HEAD_ICON), new OnRequestListener() {

                            @Override
                            public void onSuccess() {
                                if (mAsyncImageLoader != null) {
                                    mAsyncImageLoader.clearBitmap();
                                }
                                sendEmptyUiMessage(MSG_UPLOAD_SUCCESS);
                            }

                            @Override
                            public void onFailed(String errorMsg) {
                                sendEmptyUiMessage(MSG_UPLOAD_FAIL);
                            }
                        });

                break;
            case MSG_START_UPDATE_NICKNAME:
                sendEmptyUiMessage(MSG_START_MODIFY);
                if (setNickNameDialog.getNickName() == null) {
                    sendEmptyUiMessage(MSG_UPDATE_NICKNAME_FAIL);
                    return;
                }
                UserManager.getInstance().updateNickName(setNickNameDialog.getNickName(),
                        user.getAccountName(), new OnRequestListener() {

                            @Override
                            public void onSuccess() {
                                sendEmptyUiMessage(MSG_UPDATE_NICKNAME_SUCCESS);
                            }

                            @Override
                            public void onFailed(String errorMsg) {
                                sendEmptyUiMessage(MSG_UPDATE_NICKNAME_FAIL);
                                ToastUtil.showMsg(errorMsg);
                            }
                        });

                break;
            default:
                break;
        }

    };

    @Override
    public void handleUiMessage(Message msg) {
        super.handleUiMessage(msg);
        switch (msg.what) {
            case MSG_START_MODIFY:
                if (mLoadingView == null) {
                    mLoadingView = new LoadingView(getApplicationContext());
                }
                showLoadingView();
                break;
            case MSG_UPDATE_SUCCESS:
                user.setTrueName(identitySetDialog.getRealName());
                setIDInfo();
                hideLoadingView();
                ToastUtil.showMsg("设置成功");
                break;
            case MSG_UPDATE_FAIL:
                hideLoadingView();
                showIdentitySetDialog();
                identitySetDialog.etRealName.setText(realName);
                identitySetDialog.etPassword.setText(userPsw);
                identitySetDialog.etIdNum.setText(userIdNum);
                // ToastUtil.showMsg("设置失败");
                break;
            case MSG_UPLOAD_SUCCESS:
                hideSoftInput(UserInfoActivity.this);
                hideLoadingView();
                user.setHeadIconUrl(FolderManager.USER_HEAD_ICON);
                setUserHead();
                sendBroadcast(new Intent(SDKActions.ACTION_MODIFY_HEAD_SUCCESS));
                ToastUtil.showMsg("头像上传成功");
                break;
            case MSG_UPLOAD_FAIL:
                hideLoadingView();
                tvUserIdNum.setText("未绑定");
                ToastUtil.showMsg("头像上传失败");
                break;
            case MSG_UPDATE_NICKNAME_SUCCESS:
                user.setNickName(nickName);
                setNickName();
                hideLoadingView();
                ToastUtil.showMsg("昵称修改成功");
                sendBroadcast(new Intent(SDKActions.ACTION_MODIFY_HEAD_SUCCESS));
                break;
            case MSG_UPDATE_NICKNAME_FAIL:
                hideLoadingView();
                showSetNickNameDialog();
                setNickNameDialog.setNickName(nickName);
                break;
            default:
                break;
        }
    }

    @Override
    public void setupActions(ArrayList<String> actions) {
        super.setupActions(actions);
        actions.add(SDKActions.ACTION_CHANGE_TO_VIP);
        actions.add(SDKActions.ACTION_UPDATE_BIND_SECURITY_EMAIL_SUCCESS);
    }

    @Override
    public void handleBroadcast(Context context, Intent intent) {
        super.handleBroadcast(context, intent);
        String action = intent.getAction();
        if (SDKActions.ACTION_CHANGE_TO_VIP.equals(action)) {
            showVipHeadIcon();
        } else if (SDKActions.ACTION_UPDATE_BIND_SECURITY_EMAIL_SUCCESS.equals(action)) {
            checkSecurityEmail();
        }
    }

    @Override
    public void imageLoaded(Bitmap bitmap, String key) {
        if (bitmap != null && ivUserPhoto != null) {
            ivUserPhoto.setImageBitmap(bitmap);
            Animation fade_in = AnimationUtils.loadAnimation(this, Rx.anim.kg_anim_fade_in);
            fade_in.setDuration(300);
            fade_in.setInterpolator(new DecelerateInterpolator());
            ivUserPhoto.startAnimation(fade_in);
        }
    }

    private void showLoadingView() {
        mLoadingView.setText("请稍候");
        mLoadingView.setVisibility(View.VISIBLE);
    }

    private void hideLoadingView() {
        mLoadingView.setVisibility(View.GONE);
    }

    /**
     * 计算需要转换成*的字符数量
     * 
     * @param length
     * @return
     */
    private String strReplaceCount(int length) {

        String a = "";
        for (int i = 0; i < length; i++) {
            a = a + "*";
        }
        return a;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (identitySetDialog != null) {
            identitySetDialog.dismiss();
            identitySetDialog = null;
        }
    }

}
